const router = require('koa-router')()
const News = require('../class/news')
const { Fb } = require('../class/utils')
const Upload = require('../class/upload')

router.prefix('/')

// 添加新闻
router.post('/createNews.do', Upload.upload.single('file'), async ctx => {
    const form = {}
    form.title = ctx.req.body.title
    form.content = ctx.req.body.content
    form.img = 'images/' + ctx.req.file.filename   //获取文件名
    ctx.body = await Fb.callback(News.create(form))
})

// 获取新闻列表
router.post('/getNewsList.do', async ctx => {
    const form = ctx.request.body
    let nowPage = parseInt(form.nowPage) || 1
    let pageSize = parseInt(form.pageSize) || 9999999
    ctx.body = await Fb.callback(News.select(form,nowPage,pageSize))
})


// 更新新闻信息
router.post('/updateNews.do', Upload.upload.single('file'), async ctx => {
    const form = {}
    form.title = ctx.req.body.title
    form.id = ctx.req.body.id
    form.content = ctx.req.body.content
    form.img = 'images/' + ctx.req.file.filename   //获取文件名
    ctx.body = await Fb.callback(News.update(form))
})

// 删除新闻
router.post('/deleteNews.do', async ctx => {
    const id = ctx.request.body.id
    ctx.body = await Fb.callback(News.delete(id))
})

module.exports = router